const mqtt = require('mqtt');

console.log('🔍 MQTT 主题调试工具\n');
console.log('这个脚本将帮助你找出为什么在 MQTTX 中能收到消息\n');

// 连接到 MQTT Broker
const client = mqtt.connect('mqtt://broker.emqx.io:1883', {
  clientId: 'debug-tool-' + Math.random().toString(16).substr(2, 8),
  clean: true
});

const testCases = [
  { subscribe: 'server/public', publish: 'device/DEV070', shouldReceive: false },
  { subscribe: 'server/public', publish: 'server/public', shouldReceive: true },
  { subscribe: 'device/DEV070', publish: 'device/DEV070', shouldReceive: true },
  { subscribe: 'device/#', publish: 'device/DEV070', shouldReceive: true },
  { subscribe: '#', publish: 'device/DEV070', shouldReceive: true },
  { subscribe: 'server/public', publish: 'server\\public', shouldReceive: false }, // 反斜杠测试
];

let currentTest = 0;
let receivedMessages = [];

client.on('connect', () => {
  console.log('✅ 已连接到 broker.emqx.io\n');
  runNextTest();
});

function runNextTest() {
  if (currentTest >= testCases.length) {
    console.log('\n' + '='.repeat(60));
    console.log('📊 测试总结:');
    console.log('='.repeat(60));

    testCases.forEach((test, index) => {
      const received = receivedMessages[index] || false;
      const expected = test.shouldReceive;
      const status = received === expected ? '✅ 符合预期' : '❌ 异常';

      console.log(`\n测试 ${index + 1}: ${status}`);
      console.log(`  订阅: ${test.subscribe}`);
      console.log(`  发布: ${test.publish}`);
      console.log(`  预期: ${expected ? '应该收到' : '不应收到'}`);
      console.log(`  实际: ${received ? '收到了' : '未收到'}`);
    });

    console.log('\n' + '='.repeat(60));
    console.log('💡 建议:');
    console.log('   1. 检查 MQTTX 中实际订阅的主题（可能是通配符）');
    console.log('   2. 确保主题使用正斜杠 / 而不是反斜杠 \\');
    console.log('   3. 发布和订阅的主题必须完全匹配');
    console.log('='.repeat(60) + '\n');

    client.end();
    process.exit(0);
  }

  const test = testCases[currentTest];
  receivedMessages[currentTest] = false;

  console.log(`测试 ${currentTest + 1}/${testCases.length}:`);
  console.log(`  订阅主题: ${test.subscribe}`);
  console.log(`  发布主题: ${test.publish}`);
  console.log(`  预期结果: ${test.shouldReceive ? '应该收到消息' : '不应收到消息'}`);

  // 先取消所有订阅
  client.unsubscribe('#', () => {
    // 订阅测试主题
    client.subscribe(test.subscribe, (err) => {
      if (err) {
        console.error('  ❌ 订阅失败:', err);
        currentTest++;
        runNextTest();
        return;
      }

      // 等待一下，然后发布消息
      setTimeout(() => {
        const message = `Test message ${currentTest + 1}`;
        client.publish(test.publish, message, { qos: 0 });

        // 等待接收消息
        setTimeout(() => {
          const result = receivedMessages[currentTest] ? '✅ 收到消息' : '❌ 未收到消息';
          console.log(`  结果: ${result}\n`);

          currentTest++;
          runNextTest();
        }, 1000);
      }, 500);
    });
  });
}

client.on('message', (topic, message) => {
  console.log(`  📨 收到消息: "${message.toString()}" (主题: ${topic})`);
  receivedMessages[currentTest] = true;
});

client.on('error', (err) => {
  console.error('❌ MQTT 错误:', err);
  process.exit(1);
});

// 超时保护
setTimeout(() => {
  console.log('⏱️ 测试超时');
  client.end();
  process.exit(0);
}, 30000);
